import requests
import base64


def get_token():
    # client_id 为官网获取的AK， client_secret 为官网获取的SK
    ak = '7Kg7wKoGIXzt4GWHSWvmXfZG'
    sk = 'jgjjcMGrw06hKPk8TfdIecg7APdUD0a7'
    host = f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={ak}&client_secret={sk}'
    response = requests.get(host)
    if response:
        return response.json()['access_token']
    else:
        return 'error'


def registe_face(paht):
    '''
    人脸注册
    '''

    request_url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add"
    with open(paht, 'rb') as f:
        image = base64.b64encode(f.read()).decode()
    # params = "{\"image\":\"027d8308a2ec665acb1bdf63e513bcb9\",\"image_type\":\"FACE_TOKEN\",\"group_id\":\"group_repeat\",\"user_id\":\"user1\",\"user_info\":\"abc\",\"quality_control\":\"LOW\",\"liveness_control\":\"NORMAL\"}"
    params = {
        'image': image,
        'image_type': 'BASE64',
        'group_id': '1912',
        'user_id': '1'
    }
    access_token = get_token()
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/json'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        print(response.json())


def search_face(path):
    '''
    人脸搜索
    '''

    request_url = "https://aip.baidubce.com/rest/2.0/face/v3/search"
    with open(path, 'rb') as f:
        image = base64.b64encode(f.read()).decode()

    # params = "{\"image\":\"027d8308a2ec665acb1bdf63e513bcb9\",\"image_type\":\"FACE_TOKEN\",\"group_id_list\":\"group_repeat,group_233\",\"quality_control\":\"LOW\",\"liveness_control\":\"NORMAL\"}"
    params = {
        "image":image,
        'image_type':'BASE64',
        'group_id_list':'1912'
    }
    access_token = get_token()
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/json'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        score = response.json()['result']['user_list'][0]['score']
        if score>=80:
            return True
        else:
            return False


a = search_face('jj.jpg')
if a:
    print('登录成功')
else:
    print('不是本人')
